package cn.tedu.springmvc2.controller;

import cn.tedu.springmvc2.mapper.UserMapper;
import cn.tedu.springmvc2.pojo.dto.UserDTO;
import cn.tedu.springmvc2.pojo.entity.User;
import cn.tedu.springmvc2.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RequestMapping("/users")
@RestController
public class RESTfulUserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping
    public String add(UserDTO userDTO){
        User user = new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreated(new Date());
        int num =userMapper.insert(user);
        return num>0?"添加成功":"添加失败";
    }

    @PutMapping
    public String update(UserDTO userDTO){
        User user =new User();
        BeanUtils.copyProperties(userDTO,user);
        int num = userMapper.updateByUsername(user);
        return num>0?"修改成功":"修改失败";
    }

    @DeleteMapping( "/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("删除用户,id为:"+ id);
        int num= userMapper.deleteById(id);
        return num>0?"删除成功":"删除失败";
    }

    @GetMapping
    public List<UserVO> findAll(){
        return userMapper.findAll();
    }

    @GetMapping( "/{id}")
    public UserVO find(@PathVariable Integer id){
        System.out.println("查看id为:"+id+"的用户");
        return userMapper.findById(id);
    }
}
